import { Widget, _decorator, Node, Label, ProgressBar } from 'cc';
import { UIBase } from '../scriptBase/UIBase';
import { GameMgr } from '../manager/GameMgr';
import { CoinItem } from '../uiItem/CoinItem';
import { CoinMgr } from '../manager/CoinMgr';
import { StorageUtil } from '../util/StorageUtil';
import { EventMgr } from '../manager/EventMgr';
import { EventType } from '../enum/EventType';
import { CfgPassReward } from '../config/cfg_passReward';
import { MathUtil } from '../util/MathUtil';
import { UI } from '../enum/UI';
import { DtoReward } from '../dto/DtoReward';
const { ccclass, property, requireComponent } = _decorator;

@ccclass('UIPassReward')
@requireComponent(Widget)
export class UIPassReward extends UIBase {

    // @property({ type: Node })
    private btnGet: Node = null;
    // @property({ type: Node })
    private btnContinue: Node = null;
    // @property({ type: CoinItem })
    private coinItem: CoinItem = null;

    private curPassLevel: number = 0
    private targetPassLevel: number = 0
    private passRewardLevel: number = 0

    protected onLoad(): void {
        // this.btnGet = this.findNode('BtnGet')
        // this.btnContinue = this.findNode('BtnContinue')
        // this.coinItem = this.findComp('CoinItem', CoinItem)
        
        this.btnGet = this.node.getChildByName('BtnGet');
        this.btnContinue = this.node.getChildByName('BtnContinue');
        this.coinItem = this.node.getChildByName('CoinItem').getComponent(CoinItem);
    }

    public onOpen(data?: any): void {
        this.updateState()
    }

    public onClose(data?: any): void {

    }

    private updateState(): void {
        this.coinItem.init(CoinMgr.CurCoin)
        this.passRewardLevel = StorageUtil.getItem('passRewardLevel', 0)

        this.curPassLevel = GameMgr.CurPassedLevel
        this.targetPassLevel = Math.ceil(this.curPassLevel / 5) * 5

        if (this.passRewardLevel === this.targetPassLevel) this.targetPassLevel += 5

        const canGet: boolean = this.curPassLevel >= this.targetPassLevel
        this.btnGet.active = canGet
        this.btnContinue.active = !canGet
    }

    protected onBtnCloseClick(): void {
        this.close()
    }

    protected onBtnGetClick(): void {
        this.getReward()
        StorageUtil.setItem('passRewardLevel', this.targetPassLevel)
        this.updateState()
        EventMgr.emit(EventType.GetPassReward)
    }

    protected getReward(): void {
        const weights: number[] = []
        for (let i = 0; i < CfgPassReward.length; i++) {
            const passReward = CfgPassReward[i]
            weights.push(passReward.weight)
        }
        const idx: number = MathUtil.randWeight(weights)
        const passReward = CfgPassReward[idx]
        const reward: DtoReward = passReward
        this.open(UI.GetReward, [reward])
    }

}


